package com.cjm.one.security.authenticationProvider;

import com.cjm.one.security.authenticationToken.EmailCodeAuthenticationToken;
import com.cjm.one.security.authenticationToken.EmailPasswordAuthenticationToken;
import com.cjm.one.security.custom.AppCustomer;
import com.cjm.one.security.custom.CustomPasswordEncoder;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
@Slf4j
public class EmailPasswordAuthenticationProvider implements AuthenticationProvider {
    private UserDetailsService appUserDetailsService;
    @Resource
    private CustomPasswordEncoder customPasswordEncoder;
    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        String email = (String) authentication.getPrincipal();
        String password = (String) authentication.getCredentials(); // 获取密码

        AppCustomer user =(AppCustomer) appUserDetailsService.loadUserByUsername(email);
        // 检查用户是否存在
        if (user == null) {
            throw new UsernameNotFoundException("User not found with email: " + email);
        }
        String saltedInputPassword = password + user.getCustomerInfo().getSalt();
        // 校验密码
        if (!customPasswordEncoder.matches(saltedInputPassword, user.getPassword())) {
            throw new BadCredentialsException("Invalid password");
        }
        return new EmailPasswordAuthenticationToken(user, null, user.getAuthorities());
    }

    @Override
    public boolean supports(Class<?> authentication) {
        return EmailPasswordAuthenticationToken.class.isAssignableFrom(authentication);
    }
    public void setUserDetailsService(UserDetailsService userDetailsService) {
        this.appUserDetailsService = userDetailsService;
    }
}
